package com.bdqn.controller;

import com.bdqn.pojo.SysUser;
import com.bdqn.service.SysUserService;
import com.bdqn.service.SysUserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user")
public class SysUserController extends HttpServlet {
    private SysUserService sysUserService = new SysUserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        //控制参数
        String opr = req.getParameter("opr");
        switch (opr) {
            //用户登录
            case "login":
                login(req, resp);
                break;
            case "logout":
                logout(req, resp);
                break;
            default:
                break;
        }
    }

    /**
     * 登录处理
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        SysUser loginUser = sysUserService.login(account, password);
        req.getSession().setAttribute("USER_SESSION", loginUser);
        req.getRequestDispatcher("WEB-INF/jsp/frame.jsp").forward(req, resp);
    }

    //退出系统
    private void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //销毁session
        req.getSession().invalidate();
        resp.sendRedirect("WEB-INF/jsp/login.jsp");
    }
}
